using MediatR;
using RBAC.Domain.ProductionPlans;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ProductionPlans;
using System;

namespace RBAC.Write.Api.Application.Handler.ProductionPlans
{
    public class DeleteProductionPlanCommandHandler : IRequestHandler<DeleteProductionPlanCommands, APIResult<int>>
    {
        private readonly IBaseRepository<ProductionPlan> productionPlanRep;

        public DeleteProductionPlanCommandHandler(IBaseRepository<ProductionPlan> productionPlanRep)
        {
            this.productionPlanRep = productionPlanRep;
        }

        public Task<APIResult<int>> Handle(DeleteProductionPlanCommands request, CancellationToken cancellationToken)
        {
            try
            {
                if (request == null || request.ProductionPlanId <= 0)
                {
                    return Task.FromResult(new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "参数错误：ProductionPlanId 无效",
                        Data = 0
                    });
                }

                // 查询是否存在且未删除
                var model = productionPlanRep.GetModel(request.ProductionPlanId);
                if (model == null)
                {
                    return Task.FromResult(new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "记录不存在或已删除",
                        Data = 0
                    });
                }

                // 软删除
                model.IsDeleted = true;
                var affected = productionPlanRep.Update(model);

                return Task.FromResult(new APIResult<int>
                {
                    Code = affected > 0 ? APIEnums.Success : APIEnums.Fail,
                    Msg = affected > 0 ? "删除成功" : "删除失败",
                    Data = affected
                });
            }
            catch (Exception ex)
            {
                return Task.FromResult(new APIResult<int>
                {
                    Code = APIEnums.Fail,
                    Msg = "删除异常: " + ex.Message,
                    Data = 0
                });
            }
        }
    }
}
